package com.ysd.service.service;

import com.alibaba.fastjson.JSONObject;
import com.ysd.service.bean.ClockInteractionBean;
import com.ysd.service.entity.Clock;
import com.ysd.service.enums.ClockInteractionEnum;
import com.ysd.service.util.MqttMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 实现定时任务检测设备超时
 */
@Component
@Slf4j
public class DeviceTimeoutChecker {

    @Autowired
    private ClockService clockService;

    @Autowired
    private MqttMessageUtil mqttMessageUtil;

    private static final int TIMEOUT_SECONDS = 6;

    /**
     * 每秒执行一次，检查设备是否超时
     * 定期检查所有设备的最后接收时间，如果某个设备超过5秒未发送消息，则将其状态更新为“离线”。
     */
    @Scheduled(fixedRate = 1000)
    public void checkDeviceTimeout() {
        long currentTime = System.currentTimeMillis();
        ConcurrentHashMap<String, Long> lastMessageTimeMap = clockService.getLastMessageTimeMap();

        for (Map.Entry<String, Long> entry : lastMessageTimeMap.entrySet()) {
            String id = entry.getKey();
            long lastTime = entry.getValue();

            if ((currentTime - lastTime) > TIMEOUT_SECONDS * 1000) {
                // 更新设备状态为“离线”
                clockService.updateDeviceStatus(id, "离线", currentTime);
                // 从map中移除，避免重复处理
                lastMessageTimeMap.remove(id);

                // 发送闹钟离线状态给前端
//                ClockInteractionBean config = new ClockInteractionBean();
//                Map<String, Object> map = new HashMap<>();
//                List<Clock> clocks = clockService.queryClockByDeviceId(id);
//                map.put("id", clocks.get(0).getId());
//                map.put("status", 0);
//                String topic = "/user/" + clocks.get(0).getOpenId() + "/alarmStatus";
//                log.info("向前端发送闹钟离线状态信息: " + map.toString() + ",topic: " + topic);
//                mqttMessageUtil.sendToMqtt(JSONObject.toJSONString(map), topic);
            }
        }
    }

}
